//
//  HMQauthViewController.m
//  OC新浪微博
//
//  Created by wyman on 16/4/11.
//  Copyright © 2016年 wyman. All rights reserved.
//

#import "HMQauthViewController.h"
#import <Masonry.h>
#import <SVProgressHUD.h>
#import "HMNetworkTool.h"
#import "HMUserAccount.h"
#import "HMUserAccountModel.h"
#import "HMWelecomeViewController.h"
#import "AppDelegate.h"
@interface HMQauthViewController ()<UIWebViewDelegate>
@property (nonatomic, strong) UIWebView *webView;
@end

@implementation HMQauthViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupNavtationBar];
    [SVProgressHUD showWithStatus:@"加载中"];
    
    
    
}
-(void)setupNavtationBar
{
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"填充" style:UIBarButtonItemStylePlain target:self action:@selector(autoFill)];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"登录" style:UIBarButtonItemStylePlain target:self action:@selector(close)];


}

#pragma mark - 按钮事件
-(void)close
{
    [self dismissViewControllerAnimated:YES completion:nil];

    [SVProgressHUD dismiss];
}
-(void)autoFill
{
    NSString *js = @"document.getElementById('userId').value = 'wu5351513@126.com';document.getElementById('passwd').value = 'wuyan5351513'";
    
    [self.webView stringByEvaluatingJavaScriptFromString:js];




}

-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
}
-(void)loadView
{
    self.view = self.webView;
    NSURL *url = [self oauthURL];
    NSURLRequest *request = [[NSURLRequest alloc]initWithURL:url];
    self.webView.delegate = self;
    [self.webView loadRequest:request];
    
}
//拼接Qauth授权登录界面的url

-(NSURL *)oauthURL{

    NSString *urlString = [NSString stringWithFormat:@"%@?client_id=%@&redirect_uri=%@",OauthUrl,client_id,redirect_uri];
    
    return [NSURL URLWithString:urlString];

}

-(UIWebView *)webView
{
    if (_webView == nil) {
        _webView = [[UIWebView alloc]init];
    }
    return _webView;
}

-(void)webViewDidFinishLoad:(UIWebView *)webView
{

    [SVProgressHUD dismiss];

}
-(void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
{

    if (error.code == 102) {
        return;
    }

    [SVProgressHUD showErrorWithStatus:@"加载失败"];
}

//是否应该返回一个请求
-(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{

    NSString *urlString = request.URL.absoluteString;
    
    
    //判断是不是回调地址
    
    if (![urlString hasPrefix:redirect_uri]) {
        
        return YES;
        
    }else{
    
        //得到get后面的值
        NSString *query = request.URL.query;
        
        NSString *codeString = @"code=";
        //判断是不是code开头
        
        if ([query hasPrefix:@"code"]) {
            //截取
            NSString *code = [query substringFromIndex:codeString.length];
            
            //获取onetoken
            
            [[HMUserAccountModel sharedInstance] loadAccessToken:code withblock:^(HMUserAccount *userAccount, NSError *error) {
                if(error != nil){
                
                    HMLog("加载onetoken失败");
                }
                HMLog("加载onetoken成功");

                UIViewController *controller = [[HMWelecomeViewController alloc]init];
                
                
                [(AppDelegate *)([UIApplication sharedApplication].delegate) switchViewController:controller];
            }];
        
        }else
        {
            [self close];
        }
        
        return NO;
      

        
}
    
    
    return YES;
}

//私有方法,获取accesstoken

-(void)loadAccessToken:(NSString *)code{

    NSString *urlString = access_tokenString;
    
    //参数
    NSDictionary *paranms = @{
                                     @"client_id" : client_id,
     @"client_secret":client_secret,
     @"grant_type":@"authorization_code",
     @"code":code,
     @"redirect_uri":redirect_uri,
                                     };

 
    //发送请求
    [[HMNetworkTool sharedInstance] POST:urlString parameters:paranms progress:nil success:^(NSURLSessionDataTask * _Nonnull task, NSDictionary *responseObject) {
        HMLog(@"请求成功");
        HMUserAccount *userAccount = [HMUserAccount initWithDict:responseObject];
        
        HMLog(@"%@",userAccount);
        //建立模型  保存起来
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        HMLog(@"请求失败%@",error);
    }];

}






    
@end






